package ar.Location.Api.Wikipedia;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import ar.Location.Constant.Define;
import ar.Location.PlaceObject.Place;

public class WikipediaHandler extends DefaultHandler {

	boolean is_entered_entry_TAG = false;

	WikipediaPlace wPlace = null;
	ArrayList<Place> listPlaces = null;
	StringBuffer stringBuffer = new StringBuffer();

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		listPlaces = new ArrayList<Place>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub

		stringBuffer.setLength(0);

		if (localName.equals("entry")) {
			is_entered_entry_TAG = true;
			wPlace = new WikipediaPlace(Define.DS_WIKIPEDIA);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		stringBuffer.append(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		String innerText = stringBuffer.toString().trim();

		if (is_entered_entry_TAG) {
			if (localName.equals("title")) {
				wPlace.name = innerText;
			}
			if (localName.equals("summary")) {
				wPlace.description = innerText;
			}
			if (localName.equals("lat")) {
				wPlace.latitude = innerText;
			}
			if (localName.equals("lng")) {
				wPlace.longitude = innerText;
			}
			if (localName.equals("rank")) {
				wPlace.rank = innerText;
			}
			if (localName.equals("thumbnailImg")) {
				wPlace.imageUrl = innerText;
			}
			if (localName.equals("wikipediaUrl")) {
				wPlace.websiteUrl = innerText;
			}
		}

		if (localName.equals("entry")) {
			listPlaces.add(wPlace);
			is_entered_entry_TAG = false;
		}
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}

	public ArrayList<Place> getListResults() {
		if (listPlaces != null && listPlaces.size() > 0) {
			return listPlaces;
		}
		return null;
	}
}
